package com.xidian.zhiancloud.controller.emergencyManagement;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.constant.AccidentManagementConstant;
import com.xidian.zhiancloud.constant.EmergencyManagementConstant;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.controller.ledgerManagerment.relatedPart.Student;
import com.xidian.zhiancloud.controller.ledgerManagerment.relatedPart.Teacher;
import com.xidian.zhiancloud.dao.PersonnelInformationMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.emergencyManagement.EmergencyTeamManagementDTO;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.util.zyf.ExcelUtils;
import com.xidian.zhiancloud.util.zyf.StringUtils;
import com.xidian.zhiancloud.vo.emergencyManagement.EmergencyTeamManagementDTOVO;
import com.xidian.zhiancloud.vo.emergencyManagement.EmergencyTeamManagementVO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.qo.emergencyManagement.EmergencyTeamManagementQO;
import com.xidian.zhiancloud.service.emergencyManagement.EmergencyTeamManagementService;
import com.xidian.zhiancloud.vo.emergencyManagement.PersonnelInformationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 应急管理 应急队伍管理接口
 */
@RestController
@RequestMapping("/EmergencyTeamManagement")
public class EmergencyTeamManagementController extends BaseController {

    @Autowired
    private EmergencyTeamManagementService emergencyTeamManagementService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserService userService;

    @Autowired
    private PersonnelInformationMapper personnelInformationMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    /**
     * 增加应急队伍管理
     *
     * @param emergencyTeamManagementDTO 应急队伍对象
     * @return 返回是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(EmergencyTeamManagementDTO emergencyTeamManagementDTO) {
        emergencyTeamManagementDTO.getEmergencyTeamManagement().setCompanyId(getSessionUserCompanyId());
        emergencyTeamManagementDTO.getEmergencyTeamManagement().setAdderId(getSessionUserid());
        emergencyTeamManagementDTO.getEmergencyTeamManagement().setAddTime(new Date(System.currentTimeMillis()));
        Boolean res = emergencyTeamManagementService.add(emergencyTeamManagementDTO);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取应急队伍对象
     *
     * @param id 应急队伍对象的id
     * @return 应急队伍对象
     */
    @GetMapping("/getById")
    public ResultDTO<EmergencyTeamManagementDTOVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(emergencyTeamManagementService.getById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id删除应急队伍对象
     *
     * @param ids ids数组
     * @return 返回是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = emergencyTeamManagementService.deleteByIds(ids);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id修改应急队伍对象
     *
     * @param emergencyTeamManagementDTO 应急队伍对象
     * @return 返回是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(EmergencyTeamManagementDTO emergencyTeamManagementDTO) {
        emergencyTeamManagementDTO.getEmergencyTeamManagement().setCompanyId(null);
        emergencyTeamManagementDTO.getEmergencyTeamManagement().setAdderId(null);
        emergencyTeamManagementDTO.getEmergencyTeamManagement().setAddTime(null);
        Boolean res = emergencyTeamManagementService.patchById(emergencyTeamManagementDTO);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 条件查询
     *
     * @param emergencyTeamManagementQO 查询条件
     * @return 返回查询列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<EmergencyTeamManagementVO>> getListByQueryObject(EmergencyTeamManagementQO emergencyTeamManagementQO) {
        if (emergencyTeamManagementQO.getCurrent() == null || emergencyTeamManagementQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        emergencyTeamManagementQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(emergencyTeamManagementService.getListByQO(emergencyTeamManagementQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     *
     * @param response
     * @param ids      id列表
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        List<EmergencyTeamManagement> list = emergencyTeamManagementService.listByIds(Arrays.asList(ids));
        List<EmergencyTeamManagementVO> ans = new LinkedList<>();

        list.forEach(o -> {
            EmergencyTeamManagementVO vo = new EmergencyTeamManagementVO();
            BeanUtils.copyProperties(o, vo);
            Organization org = organizationService.getById(vo.getOrganizationId());
            vo.setOrganizationName(org == null ? "该部门不存在" : org.getName());

            LambdaQueryWrapper<PersonnelInformation> query = Wrappers.lambdaQuery();
            query.eq(PersonnelInformation::getEmergencyTeamId, vo.getId());
            List<PersonnelInformation> personnelInformationList = personnelInformationMapper.selectList(query);
            List<PersonnelInformationVO> personnelInformationVOList = new LinkedList<>();

            personnelInformationList.forEach(entry -> {
                PersonnelInformationVO personnelInformationVO = new PersonnelInformationVO();
                BeanUtils.copyProperties(entry, personnelInformationVO);
                SysUser user = userService.getById(personnelInformationVO.getUserId());
                personnelInformationVO.setPersonnelName(user == null ? "该用户不存在" : user.getName());
                personnelInformationVO.setPostName(EmergencyManagementConstant.PostType.get(personnelInformationVO.getPostId()));
                SysUser userid =sysUserMapper.selectById(personnelInformationVO.getUserId());
                String ids_s=userid.getOrgids();
                long[] ids_l = Arrays.stream(ids_s.split(",")).mapToLong(Long::parseLong).toArray();

                List<String> names = Arrays.stream(ids_l).mapToObj(tmp_id -> {
                    Organization p_org = organizationMapper.selectById(tmp_id);
                    return p_org == null ? "该部门已被删除" : p_org.getName();
                }).collect(Collectors.toList());

                personnelInformationVO.setOrganizationNames(StringUtils.concatStrings(names));
                personnelInformationVO.setTel(userid==null?"该用户不存在":userid.getPhone());
                personnelInformationVOList.add(personnelInformationVO);
            });
            vo.setPersonnelInformationVOList(personnelInformationVOList);
            ans.add(vo);
        });
        ExcelUtils.exportExcel(ans, "应急队伍管理", "应急队伍管理", EmergencyTeamManagementVO.class, "应急队伍管理", response);
    }
}